import 'package:account/route/AddGroupApp.dart';
import 'package:account/route/pwd.dart';
import 'package:account/utils/cus_behavior.dart';
import 'package:account/utils/my_data.dart';

import 'add.dart';
import 'package:account/utils/utils.dart';
import 'package:flutter/material.dart';
import '../bean/group.dart';

class MainPageApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MainPageAppState();
  }
}

class MainPageAppState extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainHome(),
    );
  }
}

class MainHome extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MainHomeState();
  }
}

class MainHomeState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("主页"),
        ),
        body: Column(
          children: [
            Flex(
              direction: Axis.horizontal,
              children: [
                //添加一个账号
                Expanded(
                  child: IconButton(
                      onPressed: () {
                        //显示添加dialog
                        _showAddDialog(context);
                      },
                      icon: Icon(Icons.add)),
                  flex: 1,
                ),
                //设置
                Expanded(
                  child: IconButton(
                      onPressed: () {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (context) => PwdApp()));
                      },
                      icon: Icon(Icons.settings)),
                  flex: 1,
                ),
              ],
            ),
            Container(
              height: 1,
              color: Colors.grey,
            ),
            Expanded(
                child: Container(
              padding: EdgeInsets.only(top: 5),
              child: ScrollConfiguration(
                behavior: CusBehavior(),
                child: ListView.builder(
                    itemCount: QUtils.listGroup.length,
                    itemBuilder: (context, index) {
                      return GestureDetector(
                        onLongPress: () {
                          _showDeleteGroupDialog(index);
                        },
                        child: ExpansionTile(
                            title: Text("${QUtils.listGroup[index].name}"),
                            children: _itemBuilder(index)),
                      );
                    }),
              ),
            ))
          ],
        ));
  }

  ///删除分组dialog
  ///
  /// [index] 代表[QUtils.listGroup]的下标，当前操作的是哪个分组
  _showDeleteGroupDialog(int index) async {
    Object? result = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("删除分组？"),
            titlePadding: EdgeInsets.all(10),
            content: Text("是否删除分组？"),
            contentPadding: EdgeInsets.all(10),
            actions: [
              ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context, 1);
                  },
                  child: Text("是的")),
              ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context, 0);
                  },
                  child: Text("不了"))
            ],
          );
        });
    //确定删除，执行操作
    if (result != null && result as int == 1) {
      //删除分组和相关的账号内容
      await MyData.deleteGroup(index);
      //重新获取当前账号信息
      await MyData.getAllGroupAndAccount();
      setState(() {});
    }
  }

  _showAddDialog(BuildContext context) async {
    Object? result = await showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                alignment: Alignment.center,
                width: MediaQuery.of(context).size.width,
                child: ElevatedButton(
                    child: Text("创建一个分组"),
                    onPressed: () async {
                      final Object? result = await Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => AddGroupApp()));
                      if (result == null) return;
                      Navigator.of(context).pop(result as int);
                    }),
              ),
              Container(
                alignment: Alignment.center,
                width: MediaQuery.of(context).size.width,
                child: ElevatedButton(
                    child: Text("创建一个账号"),
                    onPressed: () async {
                      if (QUtils.listGroup.length == 0) return;
                      final Object? result = await Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => AddApp(-1, -1)));
                      if (result == null) return;
                      Navigator.of(context).pop(result as int);
                    }),
              ),
              Container(
                  margin: EdgeInsets.only(top: 10),
                  alignment: Alignment.center,
                  width: MediaQuery.of(context).size.width,
                  child: Visibility(
                    visible: QUtils.listGroup.length == 0,
                    child: Text(
                      "当前没有分组，请先创建分组！",
                      style: TextStyle(
                          color: Colors.red,
                          decoration: TextDecoration.none,
                          fontSize: 16),
                    ),
                  )),
            ],
          );
        });
    if (result != null && result as int == 1) setState(() {});
  }

  List<Widget> _itemBuilder(int index) {
    List<Widget> list = [];
    if (QUtils.listGroup[index].list == null) return list;
    List<Account> aList = QUtils.listGroup[index].list!;
    for (int i = 0; i < aList.length; i++) {
      list.add(Container(
          width: MediaQuery.of(context).size.width,
          child: GestureDetector(
              onTap: () async {
                Object? result = await Navigator.push(context,
                    MaterialPageRoute(builder: (context) => AddApp(index, i)));
                if (result != null && result as int == 1) setState(() {});
              },
              onLongPress: () {
                _showDeleteAccountDialog(index, i);
              },
              child: Flex(
                direction: Axis.horizontal,
                children: [
                  Expanded(
                    flex: 1,
                    child: Container(
                        padding: EdgeInsets.only(left: 20, top: 10, bottom: 10),
                        child: Text("${aList[i].list![0].value}")),
                  ),
                  Expanded(
                    flex: 1,
                    child: Container(
                        padding:
                            EdgeInsets.only(right: 20, top: 10, bottom: 10),
                        child: Text(
                          "${aList[i].getTimeStr()}",
                          textAlign: TextAlign.end,
                        )),
                  )
                ],
              ))));
    }
    return list;
  }

  ///删除账号
  ///
  /// [index]和[position] 对应[QUtils.listGroup]及其list的下标
  _showDeleteAccountDialog(int index, int position) async {
    Object? result = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("删除账号？"),
            titlePadding: EdgeInsets.all(10),
            content: Text("是否删除账号"),
            contentPadding: EdgeInsets.all(10),
            actions: [
              ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context, 1);
                  },
                  child: Text("是的")),
              ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context, 0);
                  },
                  child: Text("不了")),
            ],
          );
        });
    //确定删除，则删除相关内容
    if (result != null && result as int == 1) {
      await MyData.deleteAccount(index, position);
      setState(() {});
    }
  }
}

@Deprecated('结构发生改变，此类过时')
class MainAccountItem extends StatelessWidget {
  final int index;
  final VoidCallback callback;

  MainAccountItem(this.index, this.callback);

  @override
  Widget build(BuildContext context) {
    return Container(
        width: MediaQuery.of(context).size.width,
        child: GestureDetector(
            onTap: () async {
              int result = await Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AddApp(index, -1)));
              if (result == 1) callback();
            },
            onLongPress: () {},
            child: Flex(
              direction: Axis.horizontal,
              children: [
                Expanded(
                  flex: 1,
                  child: Container(
                      padding: EdgeInsets.only(left: 20, top: 10, bottom: 10),
                      child:
                          Text("${QUtils.listAccount[index].list![0].value}")),
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                      padding: EdgeInsets.only(right: 20, top: 10, bottom: 10),
                      child: Text(
                        "${QUtils.listAccount[index].getTimeStr()}",
                        textAlign: TextAlign.end,
                      )),
                )
              ],
            )));
  }
}
